import React, { Component } from 'react';
import { connect } from 'dva';
// import { Tabs } from 'antd';
import styles from './index.css';
import sty from '../statistics/components/deviceComponents/commList.css';
// const { TabPane } = Tabs;
// import { createHashHistory } from 'history';
import { Select, Button, DatePicker, Spin, message } from 'antd';
import _ from 'lodash';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import { QueryOperLogStatisVo, QueryOperLogPage } from '@/models/connect';
import { Dispatch, AnyAction } from 'redux';
import { operLogPage, operLogStatisVo } from '@/services/journalManage';
import produce, { Draft } from 'immer';
import { isMenuVisible } from '@/utils/utils';
moment.locale('zh-cn');
const { Option } = Select;

interface PlatformlogProps {
  operLogStatisVo?: QueryOperLogStatisVo;
  operLogPage?: QueryOperLogPage;
  loading?: boolean;
  dispatch: Dispatch<AnyAction>;
}

class platformlog extends Component<PlatformlogProps> {
  constructor(props: PlatformlogProps) {
    super(props);
    this.state = {
      startValue: '',
      endValue: '',
      lastScrollSite: '',
      presentPageNum: 1,
      loading: true,
      parameters: {
        logType: null,
        startTime: '',
        endTime: '',
        pageNum: '1',
        pageSize: '10',
      },
      pageTotal: '',
      detailsData: [],
      tableData: [],
    };
  }

  handleTabChange = (type: string) => {
    // console.log(type);
  };
  onStartChange = (value: string | null) => {
    // setStartValue(value);
  };
  handleStartOpenChange = (open: string | null, dateString: any) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.startTime = dateString;
        draft.startValue = dateString;
      }),
    );
  };
  handleEndOpenChange = (open: string | null, dateString: any) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.endTime = dateString;
        draft.endValue = dateString;
      }),
    );
  };
  handleQuery = () => {
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.pageNum = '1';
        draft.detailsData = [];
      }),
      () => {
        this.handleFilterQuery();
      },
    );
  };
  handleLoading = async () => {
    const { dispatch } = this.props;
    this.setState({
      loading: true,
    });

    let [err, data] = await operLogStatisVo(this.state.parameters);
    if (!err) {
      this.setState({
        tableData: data,
      });
    }
    this.handleFilterQuery();
  };
  handleFilterQuery = async () => {
    // 搜索
    const { dispatch } = this.props;
    this.setState({
      loading: true,
    });
    let [err, data] = await operLogPage(this.state.parameters);
    if (!err) {
      const operLogPagelist = data.rows;
      this.setState({
        loading: false,
      });
      if (operLogPagelist != null && operLogPagelist.length != 0) {
        operLogPagelist.map(item => {
          const date1 = moment(item.operTime).format('HH:mm:ss');
          const date2 = moment(item.operTime).format('YYYY-MM-DD');
          let logText;
          if (item.status == 0) {
            logText =
              item.operTime +
              '所在部门:' +
              item.deptName +
              ',请求URL:' +
              item.operUrl +
              ',模块标题:' +
              item.title +
              ',错误消息:' +
              item.errorMsg +
              ',登录账号:' +
              item.operName +
              '操作类型：其他';
          } else if (item.status == 1) {
            logText =
              item.operTime +
              '所在部门:' +
              item.deptName +
              ',请求URL:' +
              item.operUrl +
              ',模块标题:' +
              item.title +
              ',错误消息:' +
              item.errorMsg +
              ',登录账号:' +
              item.operName +
              '操作类型：新增';
          } else if (item.status == 2) {
            logText =
              item.operTime +
              '所在部门:' +
              item.deptName +
              ',请求URL:' +
              item.operUrl +
              ',模块标题:' +
              item.title +
              ',错误消息:' +
              item.errorMsg +
              ',登录账号:' +
              item.operName +
              '操作类型：修改';
          } else if (item.status == 3) {
            logText =
              item.operTime +
              '所在部门:' +
              item.deptName +
              ',请求URL:' +
              item.operUrl +
              ',模块标题:' +
              item.title +
              ',错误消息:' +
              item.errorMsg +
              ',登录账号:' +
              item.operName +
              '操作类型：删除';
          }
          let itemdata = {
            text: logText,
            id: item.operId,
            date: date2,
            time: date1,
          };
          this.setState({
            detailsData: [...this.state.detailsData, itemdata],
            pageTotal: data.total,
          });
        });
      } else {
        message.info('查询已结束');
      }
    }
  };
  componentDidMount() {
    const scrollDiv = document.getElementById('scroll_divs'); //js的写法 上面的和这个选择一个
    const offsetHeight = scrollDiv.offsetHeight;
    //绑定事件
    scrollDiv.addEventListener('scroll', () => {
      const scrollTop = scrollDiv.scrollTop;
      const scrollHeight = scrollDiv.scrollHeight;
      if (offsetHeight + scrollTop >= scrollHeight) {
        //触发事件
        const count = this.state.presentPageNum;
        this.setState(
          produce((draft: Draft): void => {
            draft.parameters.pageNum = count + 1;
            draft.presentPageNum = count + 1;
            draft.lastScrollSite = scrollHeight;
          }),
        );
        // this.setState({
        //   lastScrollSite: scrollHeight,
        //   presentPageNum: count + 1,
        //   parameters: { pageNum: count + 1 },
        // });
        let arrylist = [];
        arrylist = this.state.detailsData;
        if (arrylist.length != this.state.pageTotal) {
          this.handleFilterQuery();
        }
        // this.setState({
        //   loading: false,
        // });
      }
    });
    // window.onscroll()
    isMenuVisible('iot:operLog:statistical') && this.handleLoading();
  }

  render() {
    const { operLogStatisVo = {}, operLogPage = [] } = this.props;
    return (
      <div className={styles['log-container']}>
        {isMenuVisible('iot:operLog:statistical') && (
          <Spin spinning={this.state.loading}>
            <div className={styles['log-con-top']}>
              <div className={styles['log-con-top-box']}>
                <p>今日</p>
                <div className={styles['log-con-top-box-tBox']}>
                  <span>{this.state.tableData.dayCount}</span>
                </div>
              </div>
              <div className={styles['log-con-top-box']}>
                <p>近一周</p>
                <div className={styles['log-con-top-box-tBox']}>
                  <span>{this.state.tableData.weekCount}</span>
                </div>
              </div>
              <div className={styles['log-con-top-box']}>
                <p>近30天</p>
                <div className={styles['log-con-top-box-tBox']}>
                  <span>{this.state.tableData.monthCount}</span>
                </div>
              </div>
            </div>

            <div className={styles['log-con-bottom']}>
              <div className={sty['inforAnasy-container-top-input dev-search']}>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>日志开始时间</span>
                  <DatePicker
                    defaultPickerValue={this.state.startValue}
                    onChange={this.handleStartOpenChange}
                    value={
                      this.state.parameters.startTime
                        ? moment(this.state.parameters.startTime)
                        : undefined
                    }
                    locale={locale}
                  />
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>日志结束时间</span>
                  <DatePicker
                    defaultPickerValue={this.state.endValue}
                    onChange={this.handleEndOpenChange}
                    value={
                      this.state.parameters.endTime
                        ? moment(this.state.parameters.endTime)
                        : undefined
                    }
                    locale={locale}
                  />
                  {/* <input type="text" /> */}
                </div>
                <Button type="link" className={styles['search']} onClick={this.handleQuery}>
                  搜索
                </Button>
                <Button
                  className={styles['search']}
                  type="link"
                  size="large"
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters.endTime = null;
                        draft.endValue = null;
                        draft.parameters.startTime = null;
                        draft.startValue = null;
                      }),
                      () => {},
                    );
                  }}
                >
                  重置
                </Button>
              </div>
              <div id="scroll_divs" className={styles['details']}>
                <div className={styles['details-box']}>
                  {this.state.detailsData.map(item => (
                    <div className={styles['details-box-tBox']} key={item.id}>
                      <div className={styles['textBox-right']}>{item.text}</div>
                      <div className={styles['textBox-left']}>
                        <p>{item.date}</p>
                        <span>{item.time}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </Spin>
        )}
      </div>
    );
  }
}
export default connect(({ loading, journalManageMode }: any) => ({
  loading: loading.effects['journalManageMode/operLogStatisVo'],
  operLogStatisVo: journalManageMode.operLogStatisVo,
  operLogPage: journalManageMode.operLogPage,
}))(platformlog);
